<?php
    require_once 'all_fns.php';

    //注册时的填写长度最小/大值
    const
        MIN_LEN_ID = 1,
        MAX_LEN_ID = 20,
        MIN_LEN_NICKNAME = 1,
        MAX_LEN_NICKNAME = 20,
        MIN_LEN_PASSWD = 4,
        MAX_LEN_PASSWD = 20;
        
         
    $id = $_POST['id'];
    $nickname = $_POST['nickname'];
    $passwd = $_POST['passwd'];
    $passwdconfirm= $_POST['passwd2'];
    $email = $_POST['email'];
    
    session_start();
    
    try 
    {
        $warnig_tryagain = "Please return back and try again.";
        
        if(!Data_Validation::is_filledout($_POST))
        {
            throw new Exception("The form is not filled out. ".$warnig_tryagain);
        }     
        
        //注意， 此处当两者分别为0000及000000之类的时候，如果使用“!=”操作符，会判断为相等；因此使用“!==”
        if($passwd !== $passwdconfirm)
        {
            throw new Exception("The passwords you entered do not matche. ".$warnig_tryagain);
        }   
        
        if(!Data_Validation::is_valid_length($id, MIN_LEN_ID, MAX_LEN_ID))
        {
            throw new Exception("The length of Wechat ID should be between ".MIN_LEN_ID." and ".MAX_LEN_ID.". ".$warnig_tryagain);
        }
        
        if(!Data_Validation::is_valid_length($nickname, MIN_LEN_NICKNAME, MAX_LEN_NICKNAME))
        {
            throw new Exception("The length of nickname should be between ".MIN_LEN_NICKNAME." and ".MAX_LEN_NICKNAME.". ".$warnig_tryagain);
        }
        
        if(!Data_Validation::is_valid_length($passwd, MIN_LEN_PASSWD, MAX_LEN_PASSWD))
        {
            throw new Exception("The length of password should be between ".MIN_LEN_PASSWD." and ".MAX_LEN_PASSWD.". ".$warnig_tryagain);
        }        
        
        if(!Data_Validation::is_valid_email($email))
        {
            throw new Exception("The email address you entered is not valid. ".$warnig_tryagain);     
        }
                
        user_controller::register_newuser($id, $nickname, $passwd, $email);

        $_SESSION[STR_valid_user] = $id;
        
        echo 'Congratulations, you\'ve been succeed registered.<br>';
        echo do_url("index.html", "Go to main page");
        
        
    } 
    catch (Exception $e) 
    {
        echo "Problem: ".$e->getMessage().'<br>';        
        
        exit;
    }
    
    
        
    
    
?>